/*
 * ******************************************************************************
 *   Copyright (c) 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.prototypes;


import it.gmariotti.cardslib.library.AnimatorListenerAdapter;
import it.gmariotti.cardslib.library.Constants;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.ResourceTable;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.VelocityDetector;
import ohos.agp.utils.Rect;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;

/**
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class SwipeDismissListItemViewTouchListener implements Component.TouchEventListener {


    /**
     * The callback interface used by {@link SwipeDismissListItemViewTouchListener} to inform its client
     * about a successful dismissal of one or more list item positions.
     */
    public interface DismissCallbacks {

        /**
         * Called to determine whether the given position can be dismissed.
         *
         * @param position
         * @param card
         * @param listObject
         * @return boolean
         */
        boolean canDismiss(int position, Card card, ListObject listObject);

        /**
         * Called when the user has indicated they she would like to dismiss one or more list item
         * positions.
         *
         * @param listView     The originating {@link ListContainer}.
         * @param position     position to dismiss
         * @param dismissRight
         */
        void onDismiss(LinearListView listView, int position, boolean dismissRight);
    }


    private ListObject mListObject;
    private LinearListView mListView;

    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private Component itemView;
    private DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private float mDownY;
    //private Card mToken;
    private boolean mSwiping;
    private VelocityDetector mVelocityTracker;
    private boolean mPaused;
    private float mTranslationX;
    private int mSwipingSlop;
    private int mDownPosition;
    private Component mDownView;

    private int swipeDistanceDivisor = 2;

    public SwipeDismissListItemViewTouchListener(LinearListView listView, DismissCallbacks callbacks) {
        mSlop = 8;
        mMinFlingVelocity = 50 * 16;
        mMaxFlingVelocity = 8000;
        mAnimationTime = 200;

        this.mListView = listView;
        mCallbacks = callbacks;
        try {
            swipeDistanceDivisor = listView.getContext().getResourceManager().getElement(ResourceTable.Integer_list_card_swipe_distance_divisor).getInteger();
        } catch (Exception e) {
            HiLog.error(Constants.LABEL_LOG, e.toString());
        }
    }


    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mListView.getWidth();
        }

        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN: {

                if (mPaused) {
                    return false;
                }

                if (mSwiping) {
                    return true;
                }

                // Find the child view that was touched (perform a hit test)

                Rect rect = new Rect();
                int childCount = mListView.getChildCount();
                int headerCount = 0;
                int footerCount = 0;
                int[] listViewCoords;
                listViewCoords = mListView.getLocationOnScreen();


                int x = (int) touchEvent.getPointerScreenPosition(0).getX() - listViewCoords[0];
                int y = (int) touchEvent.getPointerScreenPosition(0).getY() - listViewCoords[1];
                Component child = null;
                for (int i = headerCount; i < (childCount - footerCount); i++) {
                    child = mListView.getComponentAt(i);
                    if (child != null) {
                        //todo 这个方法要验证一下，rect最后是否会有值
                        child.getSelfVisibleRect(rect);
                        if (rect.isInclude(x, y)) {
                            mDownView = child;
                            break;
                        }
                    }

                }

                if (mDownView != null) {
                    mDownX = touchEvent.getPointerScreenPosition(0).getX();
                    mDownY = touchEvent.getPointerScreenPosition(0).getY();
                    mDownPosition = mListView.getPositionForView(mDownView);
                    ListObject object = mListView.getAdapter().getItem(mDownPosition);
                    if (mCallbacks.canDismiss(mDownPosition, object.getParentCard(), object)) {
                        mVelocityTracker = VelocityDetector.obtainInstance();
                        mVelocityTracker.addEvent(touchEvent);
                    } else {
                        mDownView = null;
                    }
                }
                //todo no such method
//                component.onTouchEvent(motionEvent);
                return false;

            }
            case TouchEvent.POINT_MOVE: {
                if (mVelocityTracker == null || mPaused) {
                    break;
                }

                mVelocityTracker.addEvent(touchEvent);
                float deltaX = touchEvent.getPointerScreenPosition(0).getX() - mDownX;
                float deltaY = touchEvent.getPointerScreenPosition(0).getY() - mDownY;
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);

                    mDownView.getComponentParent().moveChildToFront(mDownView);
                    mListView.getComponentParent().moveChildToFront(mListView);
                    // Cancel ListView's touch (un-highlighting the item)
                    //todo no such method
//                    TouchEvent cancelEvent = MotionEvent.obtain(motionEvent);
//                    cancelEvent
//                            .setAction(MotionEvent.ACTION_CANCEL
//                                    | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
//                    mDownView.onTouchEvent(cancelEvent);
//                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mDownView.setTranslationX(deltaX - mSwipingSlop);

                   /* mDownView.setAlpha(Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                   */
                    return true;
                }
                break;
            }

            case TouchEvent.PRIMARY_POINT_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = touchEvent.getPointerScreenPosition(0).getX() - mDownX;
                mVelocityTracker.addEvent(touchEvent);
                mVelocityTracker.calculateCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getHorizontalVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getVerticalVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / swipeDistanceDivisor) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getHorizontalVelocity() > 0;
                }
                if (dismiss && mDownPosition != ListContainer.INVALID_INDEX) {

                    // dismiss
                    dismiss(mDownView, mDownPosition, dismissRight);

                } else {
                    // cancel
                    AnimatorProperty animatorProperty = mDownView.createAnimatorProperty();
                    animatorProperty.moveFromX(mDownView.getLeft()).moveToX(0).alpha(1).setDuration(mAnimationTime);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                if (mSwiping) {
                    //To prevent onClick event with a fast swipe
                    mSwiping = false;
                    return true;
                }
                mSwiping = false;
                break;
            }

            case TouchEvent.CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

                if (mDownView != null) {
                    // cancel
                    AnimatorProperty animatorProperty = mDownView.createAnimatorProperty();
                    animatorProperty.moveFromX(mDownView.getLeft()).moveToX(0).alpha(0).setDuration(mAnimationTime);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                mSwiping = false;
                break;
            }

        }

        return false;
    }


    private void dismiss(final Component view, final int position, final boolean dismissRight) {
        if (view == null) {
            // No view, shortcut to calling onDismiss to let it deal with adapter
            // updates and all that.
            mCallbacks.onDismiss(mListView, position, dismissRight);
            return;
        }

        AnimatorProperty animatorProperty = view.createAnimatorProperty();
        animatorProperty.moveFromX(view.getLeft()).moveToX(dismissRight ? mViewWidth : -mViewWidth).alpha(0).setDuration(mAnimationTime)
                .setStateChangedListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onEnd(Animator animator) {
                        finalizeDismiss(view, position, dismissRight);
                    }
                });

    }

    private void finalizeDismiss(final Component dismissView, final int dismissPosition, final boolean dismissRight) {
        mCallbacks.onDismiss(mListView, dismissPosition, dismissRight);
    }

}
